<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>webchat</title>
        <link rel="stylesheet" type="text/css" href="css/main.css"/>
        <link rel="stylesheet" type="text/css" href="css/chart.css"/>
    </head>
    <body style="overflow-x: hidden; overflow-y: hidden;margin:0px">
        <div id="app">
            <div class="btnHead">
                <button @click="btnSendMsg"  v-bind:disable="submitDisabled">开始</button>
                <span>{{notifyMsg}}</span>
            </div>

            <div class="box">
                <div class="item" v-for="item in userList">
                    <!--用户头部-->
                    <div class="userDiv"><span>{{item.userName}}</span></div>
                    <!--使用循环动态构建-->
                    <div class="content">
                        <div>
                            <div class="talk_list" v-for="child in item.contents">
                                <!-- 如果是自己的发言则靠右，别人的发言靠左-->
                                <div :class='[child.userName==item.userName ? "talk_recordboxme" : "talk_recordboxother"]'>
                                    <span>{{child.msg}}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </body>
    <script src="./js/mqttws31.js" type="text/javascript"></script>
    <script src="./js/vue.js"></script>
    <script type="module">
        import {WebClient} from "./js/webclient.js"
        import {randomString} from "./js/common.js"

        new Vue({
            el: "#app",
            data() {
                return {
                    userList: [],
                    submitDisabled:false,
                    notifyMsg:'the clients is connecting please be wait.......',
                    clientNum:0
                };
            },
            watch: {
                clientNum(val){
                    if(this.clientNum ==20)
                        this.notifyMsg =''
                        this.submitDisabled = true
                }
            },
            mounted() {
                window.clientNum =0
                this.initData()
                this.updateMsg()
                this.autoScroll()
            },
            methods: {
                //初始化数据,构造数据
                initData() {
                    //创建20个连接客户端
                    var useName=''
                    for(var i=0;i<20;i++){
                        useName = randomString(6)
                        this.userList.push({userName: useName,webclient: '', contents: []})
                    }
                    // console.log(this.userList)
                    this.userList.forEach(
                        item => {
                            let clientObj = new Paho.MQTT.Client('47.108.233.67', 8007, item.userName)
                            let webclient = new WebClient('user1', clientObj, clientObj.path)
                            //创建连接
                            webclient.connect()
                            //修改队列中的数据
                            item.webclient = webclient
                        }
                    )
                    // console.log(this.userList)
                },
                btnSendMsg() {
                    if(window.clientNum != 20){
                        this.notifyMsg ='the clients is connecting please be wait.......'
                        return true
                    }
                    this.notifyMsg=''
                    this.submitDisabled = true
                    //遍历集合开始轮询发消息，扩展为每500毫秒发一次消息
                    let ref = this
                    this.userList.forEach(
                        item => {
                            let webclient = item.webclient
                            // console.log(this)
                            //添加到localStorage
                            //ref.addToLocal(getMessage,item.userName)
                            //测试样式
                            // item.contents.push({userName: 'agent', msg: 'what can i help you'})
                            // console.log(this.userList)

                            //定时发送消息
                            setInterval(() => {
                                let date = new Date()
                                let sendText = `I'm ${item.userName}` + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
                                //将消息收集到各客户contents 集合中
                                let getMessage = {userName: item.userName, msg: sendText}
                                webclient.send(new Paho.MQTT.Message(sendText))
                                item.contents.push(getMessage)

                            }, 1000);
                        }
                    )
                },
                updateMsg() {
                    let ref = this
                    setInterval(() => {
                        ref.userList.forEach(
                            item => {
                                //localStoge 值与内存值比较
                                let localData = window.localStorage.getItem(item.userName)
                                let localArr = JSON.parse(localData)
                                ref.clientNum = window.clientNum
                                //初始状态
                                if (localData == null) {
                                    return
                                    // } else if (!ref.containMsg(item.contents,localArr))
                                } else if (1 == 1) {
                                    item.contents.push(localArr[0])
                                    localStorage.removeItem(item.userName)
                                }
                            }
                        )
                    }, 100);
                },
                /*滚动字幕*/
                autoScroll() {
                    //通过监视器定时器去滚动
                    let ref = this
                    setInterval(() => {
                        this.userList.forEach(
                            item => {
                                //设置前length -6 的高度为0
                                if (item.contents.length > 4 ) {
                                    let spanList = document.getElementsByTagName("span");
                                    let arr = Array.from(spanList)
                                    arr.forEach(
                                        spanItem => {
                                            if (spanItem.innerText == item.userName) {
                                                //talk_recordboxme、talk_recordboxother
                                                let parentNode = spanItem.parentNode
                                                // content
                                                let parent = parentNode.parentNode.children[1]
                                                let child1 = parent.children[0]
                                                if (parent.scrollTop >= child1.scrollHeight) {
                                                    parent.scrollTop = 0;
                                                } else {
                                                    parent.scrollTop++;
                                                }
                                            }
                                        }
                                    )
                                }
                                if(item.contents.length>50){
                                    // console.log(this +"当前对象为" + item.contents)
                                    item.contents.splice(1,1)
                                }
                            }
                        )
                       // console.log(this.userList)
                    }, 10);
                },
                addToLocal(getMessage, userName) {
                    let localMsg = window.localStorage.getItem(userName)
                    let array = []
                    if (localMsg != null && localMsg != '') {
                        //先获取对象值，然后追加到数据上
                        let newArray = JSON.parse(localMsg)
                        newArray.push(localMsg)
                        window.localStorage.setItem(this.clientId, JSON.stringify(newArray))
                    } else {
                        array.push(getMessage)
                        window.localStorage.setItem(this.clientId, JSON.stringify(array));
                    }
                },
                containMsg(a, obj) {
                    for (var i = 0; i < a.length; i++) {
                        if (a[i].msg == obj[0].msg) {
                            return true;
                        }
                    }
                    return false;
                }
            }
        })
    </script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        html, body {
            width: 100%;
            height: 100%;
        }
    </style>
</html>